package com.github.pig.training.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class Assemble<T> {

    /**
     * 组装实体对象
     * 杨北平  2018-06-29
     *
     * @param t
     * @param map
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public T assmbleObj(T t, Map<String,String> map) throws InvocationTargetException,IllegalAccessException {
        Field[] fields = t.getClass().getDeclaredFields();
        for (int i=0;i<fields.length;i++) {
            String attributeName = fields[i].getName();
            if (map.containsKey(attributeName)){
                String methodName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
                try {
                    Method setMethod = t.getClass().getMethod("set" + methodName, String.class);
                    setMethod.invoke(t, map.get(attributeName));
                } catch (NoSuchMethodException e) {
                    try {
                        if (map.get(attributeName) != null && !map.get(attributeName).equals("")) {
                            Method setMethod = t.getClass().getMethod("set" + methodName, Integer.class);
                            setMethod.invoke(t, Integer.parseInt(map.get(attributeName)));
                        }
                    } catch (NoSuchMethodException e1) {
                        try {
                            if (map.get(attributeName) != null && !map.get(attributeName).equals("")) {
                                Method setMethod = t.getClass().getMethod("set" + methodName, int.class);
                                setMethod.invoke(t, Integer.parseInt(map.get(attributeName)));
                            }
                        } catch (NoSuchMethodException e2) {
                            try {
                                if (map.get(attributeName) != null && !map.get(attributeName).equals("")) {
                                    Method setMethod = t.getClass().getMethod("set" + methodName, long.class);
                                    setMethod.invoke(t, new Long(map.get(attributeName)));
                                }
                            } catch (NoSuchMethodException e3) {
                                e3.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        return t;
    }





}
